// packageA/pages/approve/askForLeave/askForLeave.js
const app = getApp();
import CommonService from '../../../../utils/service/commonService.js';
import PersonnelManager from '../../../../utils/service/PersonnelManager'
const util = require('../../../../utils/util');
import Base64 from '../../../../utils/Base64';
import Toast from '@vant/weapp/toast/toast';


Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 请假事由
        leaveReason: '',
        // 显示选择请假截止时间窗口
        showSelectLeaveEndTimePopup: false,
        // 显示选择请假开始时间窗口
        showSelectLeaveStartTimePopup: false,
        // 最大时间 - 破玩意儿log输出最大时间2026年，，，B组件赋上值就成了2035年
        maxDate: 0,
        // 最小时间
        minDate: 0,
        // 请假结束时间
        leaveEndTime: '',
        // 结束时间格式化 - 显示用
        formatEndTime: '',
        // 请假开始时间
        leaveStartTime: '',
        // 开始时间格式化 - 显示用
        formatStartTime: '',
        // 请假类型列表
        leaveTypeList: [],
        // 请假类型
        leaveType: null,
        // 选择请假类型窗口
        showSelectLeaveTypePopup: false,
        // 请假人
        applicant: null,
        // 选择人员窗口
        showSelectPeronnelsPopup: false,
        // 人员列表
        personnels: [],
        // 选择项目窗口
        showSelectProjectPopup: false,
        // 项目列表
        projects: [],
        // 当前登录用户
        user: null,
        //提交按钮禁用状态，点击“提交”后禁用，成功恢复.避免重复提交
        submitDisabled:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            //当前登录用户
            user: app.globalData.userInfo,
        });
        console.log("当前登录用户:", this.data.user);
        this.getHolidayTypeList();
        this.setMinAndMaxTime();
        this.getProjectByAuthority(this.data.user.dataAuthorityOfUser.depart)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    setMinAndMaxTime() {
        // 减少1年
        const proYear = new Date(); // 当前日期
        proYear.setFullYear(proYear.getFullYear() - 1); // 年份-1

        // 增加1年
        const folYear = new Date();
        folYear.setFullYear(folYear.getFullYear() + 1); // 年份+1
        console.log("proYear", proYear.getTime());
        console.log("folYear", folYear);
        this.setData({
            minDate: proYear.getTime(),
            maxDate: folYear.getTime()
        })
    },
    /**
     * 点击输入框，选择请假人
     * @author Man Yang
     * @date 07/15/2025
     */
    inputShowPopup(e) {
        const {
            tag
        } = e.currentTarget.dataset

        if (tag === "project") {
            console.log(this.data.projects);
            if (this.data.projects === undefined || this.data.projects === null || this.data.projects.length === 0) {
                this.showToast("项目列表为空");
                return false;
            }
            this.setData({
                showSelectProjectPopup: true,
            });
        } else if (tag === "applicant") {
            if (this.data.personnels === undefined || this.data.personnels === null || this.data.personnels.length === 0) {
                this.showToast("人员列表为空");
                return false;
            }
            this.setData({
                showSelectPeronnelsPopup: true,
            });
        } else if (tag === "leaveType") {
            if (this.data.leaveTypeList === undefined || this.data.leaveTypeList === null || this.data.leaveTypeList.length === 0) {
                this.showToast("请假类型列表为空");
                return false;
            }
            this.setData({
                showSelectLeaveTypePopup: true,
            });
        } else if (tag === "leaveStartTime") {
            this.setData({
                leaveStartTime: new Date().getTime(),
                showSelectLeaveStartTimePopup: true,
            });
        } else if (tag === "leaveEndTime") {
            this.setData({
                leaveEndTime: new Date().getTime(),
                showSelectLeaveEndTimePopup: true,
            });
        }
    },

    /**
     * 关闭选择请假人窗口
     * @author Man Yang
     * @date 07/15/2025
     */
    closeSelectPopup(e) {
        const {
            tag
        } = e.currentTarget.dataset
        if (tag === "project") {
            this.setData({
                showSelectProjectPopup: false,
            });
        } else if (tag === "applicant") {
            this.setData({
                showSelectPeronnelsPopup: false,
            });
        } else if (tag === "leaveType") {
            this.setData({
                showSelectLeaveTypePopup: false,
            });
        } else if (tag === "leaveStartTime") {
            this.setData({
                showSelectLeaveStartTimePopup: false,
            });
        } else if (tag === "leaveEndTime") {
            this.setData({
                showSelectLeaveEndTimePopup: false,
            });
        }
    },

    selectProject(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        console.log(picker);
        console.log(value);
        console.log(index);
        console.log(".........................");
        this.setData({
            showSelectProjectPopup: false,
            project: value,
            applicant:null
        });

        this.GetProjectPersonnelByAuthority([this.data.project.id])
    },

    cancelSelectProject() {
        this.setData({
            showSelectProjectPopup: false,
        })
    },
    /**
     * 选择请假人，并设置请假人字段值
     * @author Man Yang
     * @date 07/15/2025
     * @param event 事件 
     */
    selectPersonnel(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        console.log(picker);
        console.log(value);
        console.log(index);
        console.log(".........................");
        this.setData({
            showSelectPeronnelsPopup: false,
            applicant: value
        })
    },

    cancelSelectPersonnel() {
        this.setData({
            showSelectPeronnelsPopup: false,
        })
    },

    selectLeaveType(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        console.log(picker);
        console.log(value);
        console.log(index);
        console.log(".........................");
        this.setData({
            showSelectLeaveTypePopup: false,
            leaveType: value
        });
    },

    cancelSelectLeaveType() {
        this.setData({
            showSelectLeaveTypePopup: false,
        });
    },

    selectLeaveTime(event) {
        /*
        console.log(event);
        console.log(event.detail);
        console.log(new Date(event.detail));
        console.log(this.formatTimeStamp(event.detail, "YYYY-MM-DD HH:mm:ss"));
        console.log(this.data.leaveStartTime);
        console.log('select leave time....');
        */

        let tag = event.currentTarget.dataset.tag

        if (tag === "start") {
            console.log(this.formatTimeStamp(event.detail, "YYYY-MM-DD HH:mm:ss"));
            this.setData({
                formatStartTime: this.formatTimeStamp(event.detail, "YYYY-MM-DD HH:mm:ss"),
                showSelectLeaveStartTimePopup: false,
            });
        } else if (tag === "end") {
            this.setData({
                formatEndTime: this.formatTimeStamp(event.detail, "YYYY-MM-DD HH:mm:ss"),
                showSelectLeaveEndTimePopup: false,
            });
        }
    },

    cancelLeaveTime(event) {

        let tag = event.currentTarget.dataset.tag

        if (tag === "start") {
            this.setData({
                showSelectLeaveStartTimePopup: false,
            });
        } else if (tag === "end") {
            this.setData({
                showSelectLeaveEndTimePopup: false,
            });
        }

    },

    showToast(msg) {
        Toast.fail({
            type: 'html',
            context: this,
            message: `<div style="width: auto; padding: 10px 15px;">` + msg + `</div>`
        });
    },

    /**
     * 编辑请假事由
     * @param {event} event
     * @author Man Yang
     * @date 07/17/2025 
     */
    editLeaveReason(event) {
        this.setData({
            leaveReason: event.detail.value,
        });
    },

    /**
     * 提交请假条
     * @author Man Yang
     * @date 07/16/2025
     */
    async submit() {
        console.log('submit...');
        console.log(this.data.user);
        this.setData({
          submitDisabled : true
        })
        // 客户
        let company = await this.getCompanyById(this.data.user.departObj[0].companyId);

        // 当前操作用户
        let user = {
            id: this.data.user.id,
            name: this.data.user.userName,
            phone: this.data.user.personalPhone,
        }


        let authorityArr = [];
        authorityArr.push(this.data.user.depart);
        authorityArr.push(this.data.project.id);
        authorityArr.push(this.data.user.departObj[0].companyId);
        if (this.data.user.departObj[0].rid != null && this.data.user.departObj[0].rid !=""){
          authorityArr.push(this.data.user.departObj[0].rid);
        }
        if (this.data.user.departObj[0].regionId != null && this.data.user.departObj[0].regionId !=""){
          authorityArr.push(this.data.user.departObj[0].regionId);
        }
        if (this.data.user.departObj[0].fid != null && this.data.user.departObj[0].fid !=""){
          authorityArr.push(this.data.user.departObj[0].fid);
        }
        // 保存数据
        let data = {
            project: this.data.project, // 项目
            applicant: this.data.applicant, // 请假人
            leaveType: this.data.leaveType, //  请假类型
            leaveStartTime: this.data.formatStartTime, // 请假开始时间
            leaveEndTime: this.data.formatEndTime, // 请假结束时间
            leaveReason: this.data.leaveReason, // 请假事由
            company: company, // 客户（一级）
            operator: user, // 创建人
            appId: this.data.user.appId, // 平台
            authority: authorityArr // 权限
        }

        console.log("保存数据：", data);
        // 检查数据完整性
        if (!this.checkedIntegrityOfTheDataOfToBeSaved(data)) {
            return false;
        }
        console.log(data);
        console.log("do save...");
   
        PersonnelManager.saveWrittenRequestForLeave(data).then(res => {
            console.log(res);
            if (res.data.data.success) {
                Toast({
                    type: 'success',
                    message: '操作成功',
                    onClose: () => {
                        wx.navigateTo({
                            url: '/packageA/pages/approve/approveList/approveList',
                        });
                    },
                });
            }
        }).catch(err => {
          this.setData({
            submitDisabled : false
          })
            console.error(err);
        });
    },

    /**
     * 检查将要保存数据的完整性
     * @param {Object} data 要检查的对象
     * @author Man Yang
     * @date 07/17/2025 
     */
    checkedIntegrityOfTheDataOfToBeSaved(data) {

        /**
         * {Map} msg 提示消息 Map[字段]消息
         * {number} lengthLimit 长度限制 100
         * {string} stringNoEmpty 不能为空的字符串
         * {string} stringOnlyLength 长度不能超出限制的字符串
         * 以上均可提前成为参数
         */

        // 为空字段数组
        let emptyField = []
        // 字符串不能为空的字段
        let stringNoEmpty = "@:leaveStartTime,leaveEndTime,leaveReason"
        // 字符串长度不能超出限制的字段
        let stringOnlyLength = "@:leaveReason"

        // 遍历对象字段
        Object.keys(data).forEach(key => {

            // 判断字符串
            if (typeof data[key] === 'string') {
                let str = data[key].trim(); //去除空格
                // 不能为空
                if (stringNoEmpty.indexOf(key) > -1) {
                    if (str === '') {
                        emptyField.push(key);
                    }
                }
                // 长度不能超出限制，其中'100'可提取为变量
                if (stringOnlyLength.indexOf(key) > -1) {
                    if (str.length > 100) {
                        emptyField.push(key);
                    }
                }
            }
            // 数字是否为0
            if (typeof data[key] === "number" && (data[key].id === 0)) {
                emptyField.push(key);
            }

            // 数组是否为空
            if (Array.isArray(data[key]) && data[key].length === 0) {
                emptyField.push(key);
            }

            // 判断数据是否为undefined
            if (typeof data[key] === "undefined") {
                emptyField.push(key);
            }

            // 对象判断id和Name是否完整。
            if (typeof data[key] === "object" && (data[key] === null || data[key].id === 0 || data[key].name === '')) {
                emptyField.push(key);
            }
        });

        console.log("为空字段：", emptyField);
        // 当'msg'Map提前为变量时，以下两个变量可以删除。
        let msg_contact = "请联系管理员。";
        let msg_checked = "请检查。";

        let msg = new Map();
        msg["project"] = "所属项目为空，" + msg_contact
        msg["applicant"] = "请假人为空，" + msg_contact
        msg["leaveStartTime"] = "请假开始时间为空，" + msg_contact
        msg["leaveEndTime"] = "请假结束时间为空，" + msg_contact
        msg["leaveReason"] = "请假事由不能为空或长度超出限制，请保持在100个字以内."
        msg["company"] = "所属机构为空，" + msg_checked
        msg["operator"] = "创建人为空，" + msg_checked
        msg["appId"] = "平台为空，" + msg_checked
        msg["authority"] = "权限为空，" + msg_checked

        if (emptyField.length > 0) {
            this.showToast(msg[emptyField[0]])
            return false;
        }

        return true;
    },

    /**
     * 根据当前登录用户的companyId获取其顶级几个信息
     * @param {number} id 
     * @author Man Yang
     * @date 07/17/2025
     * @return Object{id,name}
     */
    async getCompanyById(id) {
        console.log("查询机构...");
        let param = {
            isAuth: false,
            className: 'depart',
            data: {
                searchAll: true,
                id: id,
                selectFields: ['id', 'name'],
                nbl: Base64.encode(util.timeFormatDay(new Date()))
            }
        }
        let company
        await CommonService.goFindList(param).then(res => {
          console.log("111111111");
          console.log(res);
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
              
                company = {
                    id: result[0].id,
                    name: result[0].name,
                }
            }
        }).catch(error => {
            console.error(error);
        });
        return company;
    },

    /**
     * 根据用户权限获取其下所有项目
     * @param {[]number} authority 
     * @author Man Yang
     * @date 07/17/2025
     * @return project list
     */
    getProjectByAuthority(authority) {
        console.log("查询项目...");
        let param = {
            isAuth: false,
            className: 'depart',
            data: {
                searchAll: true,
                isProject: true,
                dataAuthority: {
                    depart: authority
                },
                selectFields: ['id', 'name']
            }
        }
        let projectList = []
        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log("项目列表", result);
                result.forEach(r => {
                    projectList.push({
                        id: r.id,
                        name: r.name,
                    })
                });
                this.setData({
                    projects: projectList
                });
                if (projectList.length === 1) {
                  console.log("projectList[0]");
                  console.log(projectList[0]);
                    this.setData({
                        project: projectList[0]
                    });
                    this.GetProjectPersonnelByAuthority([projectList[0].id])
                }
            }
        }).catch(error => {
            console.error(error);
        });
    },

    /**
     * 获取请假类型列表
     * @author Man Yang
     * @date 07/16/2025
     */
    getHolidayTypeList() {
        let param = {
            isAuth: false,
            className: 'dictionary',
            data: {
                searchAll: true,
                key: "holidayType",
                selectFields: ['id', 'name'],
                sort:{id:1}
            }
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log(result);
                let list = []
                result.forEach(r => {
                    list.push({
                        id: r.id,
                        name: r.name
                    });
                });
                this.setData({
                    leaveTypeList: list,
                });
            }
        }).catch(error => {
            console.error(error);
        })
    },

    /**
     * 根据项目ID查询项目人员
     * @author Man Yang
     * @date 07/16/2025
     */
    GetProjectPersonnelByAuthority(projectId) {
      this.setData({
        personnels: []
      })
        let data = {
            // authority: this.data.user.dataAuthorityOfUser.depart
            // id: [102097, 102219, 102221]
            id: projectId,
            state:1
        }
        console.log("当前登录用户权限：", this.data.user.dataAuthorityOfUser.depart);
        PersonnelManager.findProjectPerspnnelByAuthority(data).then(res => {
            console.log(res);
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                this.setData({
                    personnels: result
                })
            }
        }).catch(err => {
            console.error(err);
        });
    },

    /**
     * 将时间戳专为指定格式字符串
     * @param {number} timestamp    时间戳 
     * @param {string} format       格式字符串 如 'YYYY-MM-DD HH:mm:ss'
     * @author Man Yang
     * @date 07/16/2025
     */
    formatTimeStamp(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
        let date = new Date(timestamp);
        let pad = num => num.toString().padStart(2, '0');

        let replacements = {
            'YYYY': date.getFullYear(),
            'MM': pad(date.getMonth() + 1),
            'DD': pad(date.getDate()),
            'HH': pad(date.getHours()),
            'mm': pad(date.getMinutes()),
            'ss': pad(date.getSeconds())
        };

        return format.replace(/YYYY|MM|DD|HH|mm|ss/g, match => replacements[match]);
    },

    /**
     * 跳转到请假记录页面
     * @author Man Yang
     * @date 07/17/2025
     */
    goToRecord() {
        wx.navigateTo({
            url: '/packageA/pages/approve/leaveRecord/leaveRecord',
        })
    },
})